package top.chenyaohua.http;

import java.io.IOException;
import java.io.OutputStream;

public class RequestOutputStream extends OutputStream {


    private volatile boolean flag = true;

    private OutputStream outputStream;

    private HttpResponse httpResponse;

    public RequestOutputStream (OutputStream outputStream) {
        super();
        if(outputStream == null){
            throw new RuntimeException("不能为空");
        }
        this.outputStream = outputStream;
    }

    @Override
    public void write (byte[] b) throws IOException {
        if(flag){
            flag = false;
            outputStream.write(httpResponse.toString().getBytes());
        }
        outputStream.write(b);
    }

    @Override
    public void write (byte[] b, int off, int len) throws IOException {
        if(flag){
            flag = false;
            outputStream.write(httpResponse.toString().getBytes());
        }
        outputStream.write(b, off, len);
    }

    @Override
    public void flush () throws IOException {
        outputStream.flush();
    }

    @Override
    public void close () throws IOException {
        outputStream.close();
        super.close();
    }

    @Override
    public void write (int b) throws IOException {
        if(flag){
            flag = false;
            outputStream.write(httpResponse.toString().getBytes());
        }
        outputStream.write(b);
    }

    /**
     * 设置 为保护类型 防止用户调用
     * @return
     */
    protected void setHttpResponse (HttpResponse httpResponse) {
        this.httpResponse = httpResponse;
    }
}
